#include "network.h"

cClient::cClient()
{
    //ctor
    ListenerThread = NULL;
    Connected = false;
}

cClient::~cClient()
{
    //dtor
    //Stop the thread
    SDL_KillThread( ListenerThread );
    //close the socket
    SDLNet_TCP_Close(socket);
}

void cClient::StartThreads()
{
    //Create and run the thread +
    ListenerThread = SDL_CreateThread( &listener, this );
}

int cClient::listener( void *data )
{ //While the program is not over
    cout << "Starting client listener Thread..." << endl;
    int result;
    char in_msg[MAXLEN];
    bool quit=false;

    while( quit == false )
        {
        memset(in_msg, 0, MAXLEN); // Clear in buffer
        if ( ((cClient*)data)->Connected)//If I'm connected...
            {
                result=SDLNet_TCP_Recv(((cClient*)data)->socket,in_msg,MAXLEN);//Check for incoming data
                    if(result<=0)
                        {
                            //NO DATA
                            // TCP Connection is broken. (because of error or closure)
                            SDLNet_TCP_Close(((cClient*)data)->socket);
                            cout << "Socket closed..." << endl;
                            ((cClient*)data)->Connected = false;
                            quit=true;
                        }

                stringstream idmsg;
                idmsg << "/" <<((cClient*)data)->UID  << in_msg;// I will add the UID from the client to the incoming message
                try{
                    SDL_SemWait(((cClient*)data)->_server->ClientsLock);//lock smaphore to prevent client to freeze
                    cout << idmsg.str();//only for debuging

                    if  (((cClient*)data)-> Login==true)//Am I loged in?
                        {
                            ((cClient*)data)->_server->InputQueue.push(idmsg.str());  //I'm logged in
                        }else{
                            ((cClient*)data)->_server->LoginQueue.push(idmsg.str());  //New player requests
                        }
                    SDL_SemPost(((cClient*)data)->_server->ClientsLock);//unlock smaphore
                    }
                catch(exception& e)
                    {
                        cout << "QUEUE IN ERROR: " << e.what() << endl;
                    }
            }//if connected
        }//while
    cout << "Closing client listener thread..." <<endl;
    return 0;
}

void cClient::Send(const char* Msg)
{
    if (Connected==true)
        {
            int len;
            int result;
            len=strlen(Msg+1); // add one for the terminating NULL
            result=SDLNet_TCP_Send(socket,Msg,len);
            if(result<len) //If I can't send data probably I've been disconnected so....
                {
                    cout << "SDLNet_TCP_Send: " << endl << SDLNet_GetError();
                    Connected = false;
                }
        }else{
            cout << "Not connected!!" << endl;
            }
}

void cClient::SockSend(NetCommand Command, const char* Msg)//Send message
{
    if (Connected==true)
        {

        int len;
        int result;
        stringstream Out;
        Out << "/" << Command << "/" << Msg << "/";

        //len=strlen(Msg)+1; // add one for the terminating NULL
        len=strlen(Out.str().c_str())+1; // add one for the terminating NULL

        result=SDLNet_TCP_Send(socket,Out.str().c_str(),len);
        if(result<len)Connected = false;//If I can't send message, probably I'm disconnected so....
        }
}
